import request from '@/utils/request'
import { JSEncrypt } from 'jsencrypt'


/**
 * rsa公钥加密
 * @param password
 * @param publicKey
 * @returns {PromiseLike<ArrayBuffer>}
 */
export function encrypt(password, publicKey) {
  let encrypt = new JSEncrypt()
  encrypt.setPublicKey(publicKey)
  return encrypt.encrypt(password)
}
/**
 * rsa 私钥解密
 * @param password
 * @param publicKey
 * @returns {PromiseLike<ArrayBuffer>}
 */
export function decrypt(password, privateKey) {
  let encrypt = new JSEncrypt()
  encrypt.setPublicKey(privateKey)
  return encrypt.decrypt(password)
}

/**
 * 获取后端公钥
 * @param password
 * @param publicKey
 * @returns {PromiseLike<ArrayBuffer>}
 */
export function getPublicKey() {
  return request({
    url: '/publicKey',
    method: 'get',
  })
}


// 登录方法
export function login(username, password, code, uuid, publicKey) {
  const data = {
    username,
    password,
    code,
    uuid,
    publicKey
  }
  return request({
    url: '/login',
    method: 'post',
    data: data
  })
}

// 手机号验证码登录方法
export function loginPhone(username, code) {
  const data = {
    username,
    code,
  }
  return request({
    url: '/login',
    method: 'post',
    data: data
  })
}

// 获取用户详细信息
export function getInfo() {
  return request({
    url: '/getInfo',
    method: 'get'
  })
}

// 退出方法
export function logout() {
  return request({
    url: '/logout',
    method: 'post'
  })
}

// 获取验证码
export function getCodeImg() {
  return request({
    url: '/captchaImage',
    method: 'get'
  })
}
// 单点登录方法
export function bsSsoLogin(token) {
  const data = {
    token,
  }
  return request({
    url: '/project/tieling/bsSsoLogin',
    method: 'post',
    data: data
  })
}
// 获取短信验证码
export function getVerifyCode(phoneNumber) {
  return request({
    url: `/front/sms/smsCode/${phoneNumber}`,
    method: 'post'
  })
}

export function getQueryString(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  if (window.location.href.split("#/")[0].indexOf("?") < 0) {
    return null;
  }
  let r = window.location.href.split("#/")[0].split("?")[1].match(reg);
  if (r != null) return decodeURIComponent(r[2]);
  return null;
}
